package com.next.aappublicapp.views;

import java.util.List;

import org.apache.http.ParseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.util.StringUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Session;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.google.gson.JsonArray;
import com.next.aappublicapp.FullFacebookPostContentActivity;
import com.next.aappublicapp.FullImageActivity;
import com.next.aappublicapp.LoginActivity;
import com.next.aappublicapp.PostFacebookCommentActivity;
import com.next.aappublicapp.R;
import com.next.aappublicapp.handlers.ItemClickHandlerImpl;
import com.next.aappublicapp.handlers.ItemListClickHandler;
import com.next.aappublicapp.server.service.DataServices;
import com.next.aappublicapp.tasks.DownloadImageTaskParam;
import com.next.aappublicapp.tasks.FacebookAsyncTask;
import com.next.aappublicapp.util.AlertDialogUtil;
import com.next.aappublicapp.util.FacebookUtil;
import com.next.aappublicapp.util.JsonUtil;
import com.next.aappublicapp.util.TrackerUtl;
import com.nostra13.universalimageloader.core.ImageLoader;

public class FacebookPost extends LinearLayout {

	private Button likeButton ;
	private Button commentButton ;
	private int likeCounts;
	
	public FacebookPost(Context context, AttributeSet attrs, JSONObject postJson,List<DownloadImageTaskParam> downloadImageTaskParams,ItemListClickHandler itemClickedHandler) {
		super(context, attrs);
		createFacebookPost(context, R.layout.facebook_post_view, postJson,downloadImageTaskParams);
	}
	public FacebookPost(Context context, JSONObject postJson,List<DownloadImageTaskParam> downloadImageTaskParams,ItemListClickHandler itemClickedHandler) {
		super(context);
		createFacebookPost(context, R.layout.facebook_post_view, postJson,downloadImageTaskParams);
	}
	private void createFacebookPost(final Context context, int viewId, final JSONObject postJson,List<DownloadImageTaskParam> downloadImageTaskParams) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(viewId, this);
        
        ImageView postContentImage = (ImageView)view.findViewById(R.id.postContentImage);
        TextView userName = (TextView)view.findViewById(R.id.userName);
        TextView postTime = (TextView)view.findViewById(R.id.postTime);
        TextView postContent = (TextView)view.findViewById(R.id.postContent);
        likeButton = (Button)view.findViewById(R.id.likeButton);
        commentButton = (Button)view.findViewById(R.id.commentButton);
        ImageView playImage = (ImageView)view.findViewById(R.id.playImage);
        
        try {
			userName.setText("Aam Aadmi Party");
			postTime.setText(postJson.getString("created_time"));
			String postMessage = JsonUtil.getSringFromJsonObject(postJson,"message");
			if(postMessage == null){
				
			}else{
				if(postMessage.length() > 250){
					//Spanned spanned = Html.fromHtml(postMessage.substring(0, 250)+"...  <a href='http://www.google.com'>Continue Reading</a>");
					Spanned spanned = Html.fromHtml(postMessage.substring(0, 250)+"... (click to read more)");
					postContent.setText(spanned);
					
					postContent.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							
							Intent intent = new Intent(getContext(), FullFacebookPostContentActivity.class);
							Bundle bundle = new Bundle();
							
							bundle.putSerializable(FullFacebookPostContentActivity.POST_JSON_OBJECT,postJson.toString());
							intent.putExtra(FullFacebookPostContentActivity.ARGS_BUNDLE, bundle);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							getContext().startActivity(intent);

						}
					});
					
				}else{
					postContent.setText(postMessage);	
				}
			}
			
			String postType = JsonUtil.getSringFromJsonObject(postJson,"type");
			String imageUrl = JsonUtil.getSringFromJsonObject(postJson,"picture");
			//Log.i("Ravi", "source="+link);
			final String youtubeVideoId = extractYoutubeVideoId(postJson);
			//Log.i("Ravi", "postType="+postType);
			//Log.i("Ravi", "imageUrl="+imageUrl);
			//Log.i("Ravi", "youtubeVideoId="+youtubeVideoId);
			
			if(imageUrl == null || imageUrl.trim().isEmpty()){
				postContentImage.setVisibility(GONE);
				playImage.setVisibility(View.GONE);
			}else{
				postContentImage.setVisibility(VISIBLE);
				final String finalImageUrl = imageUrl = StringUtils.replace(imageUrl, "_s.", "_b.");
				//new DownloadImageTask(postContentImage).execute(imageUrl);
				ImageLoader.getInstance().displayImage(finalImageUrl, postContentImage);
				if(postType.equals("video") && youtubeVideoId != null){
					playImage.setVisibility(View.VISIBLE);
					postContentImage.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							

							// String videoId = uri.getQueryParameter("v");

							Intent lVideoIntent = YouTubeStandalonePlayer.createVideoIntent(
									(Activity) context, ItemClickHandlerImpl.DEVELOPER_KEY, youtubeVideoId,
									0, true, false);
							if (lVideoIntent != null) {
								if (ItemClickHandlerImpl.canResolveIntent(getContext(), lVideoIntent)) {
									((Activity) context).startActivityForResult(lVideoIntent,
											ItemClickHandlerImpl.REQ_START_STANDALONE_PLAYER);
								} else {
									// Could not resolve the intent - must need to install or
									// update the YouTube? API service.
									YouTubeInitializationResult.SERVICE_MISSING.getErrorDialog(
											(Activity) context, ItemClickHandlerImpl.REQ_RESOLVE_SERVICE_MISSING)
											.show();
								}
							}
						}
					});
					
				}else{
					playImage.setVisibility(View.GONE);
					postContentImage.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							
							Intent intent = new Intent(getContext(), FullImageActivity.class);
							Bundle bundle = new Bundle();
							bundle.putString(FullImageActivity.IMAGE_URL, finalImageUrl);
							intent.putExtra(FullImageActivity.ARGS_BUNDLE, bundle);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							getContext().startActivity(intent);

						}
					});
				}
				
				//downloadImageTaskParams.add(new DownloadImageTaskParam(postContentImage, imageUrl));
			}
			
			
			//Now update like and comment buttons
			likeCounts = postJson.getJSONObject("likes").getInt("count");
			boolean iHaveLikedThePost = haveILikedThePost(postJson);
			
			likeButton.setVisibility(View.VISIBLE);
			if(iHaveLikedThePost){
				likeButton.setText("Liked");
				likeButton.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						int duration = Toast.LENGTH_SHORT;
						Toast toast = Toast.makeText(getContext(), "You have already liked the post.", duration);
						toast.show();	
					}
				});
			}else{
				likeButton.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Log.i("Ravi", "Clicked on Like button");
						likePost(postJson);

					}
				});
			}
			likeButton.setText(likeButton.getText()+"("+likeCounts+")");

			
			commentButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Log.i("Ravi", "Clicked on comment button");
					if(!FacebookUtil.isFacebookLoggedIn()){
						AlertDialogUtil.showDIalog(getContext(), "Error", "You must login via facebook to use this feature");
						return;
					}
					String id;
					try {
						id = postJson.getString("id");
						Log.i("Ravi", "id="+id);
						Intent intent = new Intent(getContext(), PostFacebookCommentActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString(PostFacebookCommentActivity.ARGS_FACEBOO_POST_ID, id);
						intent.putExtra(PostFacebookCommentActivity.ARGS_BUNDLE, bundle);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						getContext().startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
					}
					

				}
			});
			
			
			
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
        
	}
	private boolean haveILikedThePost(JSONObject jsonPost) throws JSONException{
		String facebookUserId = FacebookUtil.getFaceookUserId(getContext());
		boolean iHaveLikedThePost = false;
		if(facebookUserId != null){
			
			JSONArray peopleWhoLiked = jsonPost.getJSONObject("likes").getJSONArray("data");
			for(int i=0;i<peopleWhoLiked.length();i++){
				if(peopleWhoLiked.getJSONObject(i).getString("id").equals(facebookUserId)){
					iHaveLikedThePost = true;
					break;
				}
			}
		}
		return iHaveLikedThePost;
	}
	private String extractYoutubeVideoId(JSONObject jsonPost){
		String link = JsonUtil.getSringFromJsonObject(jsonPost, "link");
		Log.i("Ravi", "link="+link);
		String youtubeVideoId = null;
		if(link == null){
			return youtubeVideoId;
		}
		if(link.contains("youtu.be")){
			Log.i("Ravi", "youtu.be="+link);
			String[] splitted = link.split("/");
			youtubeVideoId = splitted[splitted.length - 1];
			Log.i("Ravi", "youtubeVideoId="+youtubeVideoId);
			if(youtubeVideoId.contains("?")){
				youtubeVideoId = youtubeVideoId.split("?")[0];
			}
			Log.i("Ravi", "youtubeVideoId="+youtubeVideoId);
			return youtubeVideoId;
		}
		return youtubeVideoId;
	}
	private void likePost(final JSONObject jsonObject){
		Log.i("Ravi", "Liking post");
		if(!FacebookUtil.isFacebookLoggedIn()){
			AlertDialogUtil.showDIalog(getContext(), "Error", "You must login via facebook to use this feature");
			return;
		}
		FacebookUtil.checkPermission((Activity)getContext(), "publish_stream");
		new FacebookAsyncTask<String, String, Boolean>("FacebookPost","Like") {
			@Override
			protected void beforeExecute() {
				likeButton.setText("Liked("+(likeCounts+1)+")");
				
			}
			@Override
			protected Boolean doInBackground(String... params) {
				String id;
				try {
					id = jsonObject.getString("id");
					Log.i("Ravi", "id="+id);
					return DataServices.getInstance().likeFacebookPost(id,Session.getActiveSession().getAccessToken());
				} catch (Exception e) {
					e.printStackTrace();
				}
				return false;
			}
			@Override
			protected void afterExecute(Boolean result) {
				if(result){
					TrackerUtl.sendFacebookEvent("Like");
					if(likeButton != null){
						likeButton.setText("Liked("+(likeCounts+1)+")");
					}
				}else{
					TrackerUtl.sendFacebookEvent("LikeFailed");
					if(likeButton != null){
						likeButton.setText("Like("+likeCounts+")");
					}
					
				}
			}
		}.execute();
		
	}
	
}
